package com.jf.exam.controller;


import com.jf.exam.pojo.data.StudentDO;
import com.jf.exam.pojo.data.TeacherDO;
import com.jf.exam.pojo.vo.ManageVO;
import com.jf.exam.security.shiro.UsernamePasswordTypeToken;
import com.jf.exam.service.ManageService;
import com.jf.exam.utils.DataUtils;
import com.jf.exam.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 管理登陆的操作
 */

@Controller
public class LoginController {

    @Autowired
    ManageService manageService;

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    /**
     * 角色：role
     * 1. 学生
     * 2. 教师
     * 3. 管理员
     */
    @RequestMapping("/login/do")
    public String doLogin(String username, String password, String verify, int role, Model model, HttpSession httpSession) {
        Subject subject = SecurityUtils.getSubject();
        try {
            switch (role) {
                case 1:
                    subject.login(new UsernamePasswordTypeToken(username,
                            password, UsernamePasswordTypeToken.STUDENT));
                    //获取登录的信息，存入session域
                    StudentDO student = (StudentDO) subject.getPrincipal();
                    httpSession.setAttribute("student", student);
                    return "student/index";
                case 2:
                    subject.login(new UsernamePasswordTypeToken(username,
                            password, UsernamePasswordTypeToken.TEACHER));
                    //获取登录的信息，存入session域
                    TeacherDO teacherDO = (TeacherDO) subject.getPrincipal();
                    httpSession.setAttribute("teacher", teacherDO);
                    return "teacher/index";
                case 3:
                    subject.login(new UsernamePasswordTypeToken(username,
                            password, UsernamePasswordTypeToken.ADMIN));
                    //获取登录的信息，存入session域
                    ManageVO manager = (ManageVO) subject.getPrincipal();
                    httpSession.setAttribute("manager", manager);
                    return "admin/index";
            }
        } catch (AuthenticationException e) {
            e.printStackTrace();
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
        return "login";
    }

    /**
     * 校验验证码
     * 返回json格式的数据
     * {code:200,msg:验证成功}
     */
    @RequestMapping("/login/verify")
    @ResponseBody
    public Result verify(String verify, HttpSession session) {
        return DataUtils.checkVerify(verify, session);
    }


}
